package com.csust.automaticteach.controller;

import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;
import com.csust.automaticteach.manager.verifyCode.MyCaptchaService;
import com.google.code.kaptcha.Producer;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @ClassName CaptchaController
 * @Description  验证码控制器
 * @Author 钰玟
 * @Date 2025/8/17 下午6:13
 * Version 1.0
 **/

@RestController
@RequestMapping("/captcha")
@Slf4j
public class CaptchaController {
    @Resource
    private CaptchaService captchaService;
    @Resource
    private Producer kaptchaProducer;

    @Resource
    private MyCaptchaService myCaptchaService;//数字/字母验证码
    /**
     * 获取滑动验证码
     * @param captchaType 验证码类型
     * @return 验证码
     */
    @RequestMapping(value = "/get", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseModel get(@RequestParam(value = "type", defaultValue = "slide") String captchaType) {
        log.info("获取验证码,验证码类型:{}", captchaType);
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaType(captchaType);
        return captchaService.get(captchaVO);
    }

    /**
     * 验证滑动验证码
     * @param captchaVO 验证码参数
     * @return 验证结果
     */
    @PostMapping("/check")
    public ResponseModel check(@RequestBody CaptchaVO captchaVO) {
        ResponseModel checked = captchaService.check(captchaVO);

        log.info("验证验证码,验证码校验结果:{}", checked.isSuccess());
        return checked;
    }

    /**
     * 获取数字/字母图片验证码
     * @param response 响应
     * @param request 请求
     * @throws IOException 抛出IO异常
     */
    @GetMapping("/image")
    public void getImageCaptcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 清除浏览器缓存
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        // 创建验证码文本
        String capText = kaptchaProducer.createText();
        // 获取会话ID
        String sessionId = request.getSession().getId();
        // 存储验证码
        myCaptchaService.storeCaptcha(sessionId, capText);
        // 创建验证码图片
        BufferedImage image = kaptchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        // 输出图片
        ImageIO.write(image, "jpg", out);
        out.flush();
        out.close();
    }

}
